package cs342.uwosh.edu.QuizApp;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import cs342.uwosh.edu.QuizApp.storage.Quiz;
import cs342.uwosh.edu.QuizApp.thread.AsyncMethod;
import cs342.uwosh.edu.QuizApp.thread.QuizXMLParser;

import cs342.uwosh.edu.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Toast;

public class QuizListActivity extends Activity {
	private static final String getQuizURL = "http://cs346.cs.uwosh.edu/students/klappt98/quizDownload.php?quizname=";
	private ExpandableListAdapter listAdapter;
    public ArrayList<String> courseNames;
    public ArrayList<String> courseQuizzes;
    public ArrayList<ArrayList<String>> quizzes;
    public static Quiz quiz;
    String username;
	
    /** Called when the activity is first created. */
    @SuppressWarnings("unchecked")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.quizlist);
        Intent me = this.getIntent();
        username = me.getStringExtra("user");
        System.out.println("USERNAME : "+ username);
        courseNames = new ArrayList<String>();
		courseQuizzes = new ArrayList<String>();
		quizzes = new ArrayList<ArrayList<String>>();

	
		 ExpandableListView quizListView = (ExpandableListView)findViewById(R.id.expandableListView1);

		 //code to get courseNames
		 	String url = "http://cs346.cs.uwosh.edu/students/klappt98/quizList.php";
 	
		 	AsyncMethod<QuizListActivity> downloadQuiz = new AsyncMethod<QuizListActivity>(QuizListActivity.class, this, "readTextFromURL");
		 	downloadQuiz.execute(url);
		 	downloadQuiz.getResult();

		 	
		 
		
		 //WHEN USER CLICKS A QUIZ ON THE LIST:
		 quizListView.setOnChildClickListener(new OnChildClickListener()
	        {
	            
	            //@Override
	            public boolean onChildClick(ExpandableListView parent, View view, int groupPosition, int childPosition, long id)
	            {

	            	String quizName = (String)listAdapter.getChild(groupPosition, childPosition);
	            	Toast.makeText(getBaseContext(), quizName + " quiz loading", Toast.LENGTH_LONG).show();

	               // Intent i = new Intent();
	               // i.setClassName("cs342.uwosh.edu.edu.QuizApp", "cs342.uwosh.edu.QuizApp.QuizAppActivity");
	               // i.putExtra("uwosh.cs342.project1.groupID", "z0r");
	                /*i.putExtra("Example", "bob"); */
	               	
	                //PHP PAGE TO DOWNLOAD QUIZ:
	            	//TODO: ALEX INSERT CODE TO LAUNCH THE QUIZ HERE:
	            	
	            	// grab quiz XML from cloud
	        		AsyncMethod<QuizListActivity> thread = new AsyncMethod<QuizListActivity>(QuizListActivity.class, QuizListActivity.this, "getQuizXML");
	        		thread.execute(quizName);
	        		String rawXML = (String) thread.getResult();
	        		
	        		System.out.println(rawXML);
	        		
	        		// parse quiz XML
	        		QuizXMLParser parser = new QuizXMLParser();
	        		quiz = parser.buildQuiz(rawXML);
	        		
	        		if(quiz.getQuestionCount() == 0) {
	        			System.err.println("TakeQuizActivity - there are no questions in this quiz");
	        		}
	        		
	        		//Initialize Quiz
	        		quiz.start();
	        		
	        		Intent i = new Intent(QuizListActivity.this, TakeQuizActivity.class);
	        		i.putExtra("user", username);
	        		startActivity(i);
	        		
	            	
	                //String url2 = "http://cs346.cs.uwosh.edu/students/klappt98/quizDownload.php?quizname=" +quizName;
	            	
	            	return false; 
	            }
	            
	        });
		 
	        listAdapter = new ExpandableListAdapter(this, courseNames, quizzes);
	        quizListView.setAdapter(listAdapter);
	        

		 
    }
    
    @SuppressWarnings("unchecked")
	public boolean readTextFromURL(String urlS)
    {

    	URL url;
        HttpURLConnection connection = null;  
        try 
        {
          //Create connection
        	System.out.println("LOLTESTBEFRE");
            url = new URL(urlS);
            connection = (HttpURLConnection)url.openConnection();


          //Get Response from PHP, just a text message, not really required.  
          InputStream is = connection.getInputStream();
          BufferedReader rd = new BufferedReader(new InputStreamReader(is));
          String line;


          String[] splitLine;
          String lastCourse= "";
          while((line = rd.readLine()) != null) {
        	  if(line.equals(""))
        	  {
        		  quizzes.add((ArrayList<String>) courseQuizzes.clone());
        		  break;
        		  
        	  }
        	  System.out.println(line);

              splitLine = line.split(" \\| ");
              
        	  System.out.println(splitLine[0] + "AAAAAA"+ splitLine[1]);
              if(lastCourse.equals(splitLine[1]))
              {
            	  courseQuizzes.add(splitLine[0]);            	  
              }
              else if (!lastCourse.equals("") && !lastCourse.equals(splitLine[1]))
              {
            	  quizzes.add((ArrayList<String>) courseQuizzes.clone());
            	  courseQuizzes.clear();
            	  lastCourse = splitLine[1];
            	  courseNames.add(lastCourse);
            	  courseQuizzes.add(splitLine[0]);
              }
              else if (lastCourse.equals(""))
              {
            	  lastCourse=splitLine[1];
            	  courseNames.add(lastCourse);
            	  courseQuizzes.add(splitLine[0]);
              }
          }
          rd.close();

        } 
        catch (Exception e) 
        {   

          e.printStackTrace();
        } 
        finally 
        {   
          if(connection != null) 
            connection.disconnect(); 
        }
        return true;
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
    	Intent myIntent = new Intent(this,ScoreHistoryActivity.class);
    	myIntent.putExtra("z", username );
    	switch (item.getItemId()) {
    	case R.id.scores:
    		startActivity(myIntent);
    		break;
    	}
    	return true;
    }
    
    public String getQuizXML(String quizName) {
		URL quizURL;
		String xml = null;
		try {
			quizURL = new URL(getQuizURL + quizName);
			xml = new java.util.Scanner(quizURL.openStream()).useDelimiter("\\A").next();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return xml;
	}
    
}





   
    
    
